C++ Basics

Recursivity

THIS KIND OF APPROACH SHOULD NOT BE USED INSIDE AN EMBEDDED DEVICE FOR A FEW REASONS. THE MOST IMPORTANT ONES ARE:

  • Recursive functions can use up stack space very quickly, so if stack space is tight, it's better not to use recursion.
  • Poor performance

Recursivity is the property that functions have to be called by themselves. It is useful for some tasks, such as sorting elements, or calculating the factorial of numbers. For example, in order to obtain the factorial of a number (n!) the mathematical formula would be:

n! = n (n-1) (n-2) (n-3) ... 1

More concretely, 5! (factorial of 5) would be:

5! = 5 4 3 2 1 = 120

And a recursive function to calculate this in C++ could be:

// factorial calculator
#include <iostream>
using namespace std;

long factorial (long a)
{
  if (a > 1)
   return (a * factorial (a-1));
  else
   return 1;
}

int main ()
{
  long number = 9;
  cout << number << "! = " << factorial (number);
  return 0;
}

Result

9! = 362880

Notice how in function factorial we included a call to itself, but only if the argument passed was greater than 1, since, otherwise, the function would perform an infinite recursive loop, in which once it arrived to 0, it would continue multiplying by all the negative numbers (probably provoking a stack overflow at some point during runtime).